package com.xbb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbb.entity.User;
import com.xbb.entity.UserParam;
import com.xbb.service.UserService;
import com.xbb.util.MD5;
import com.xbb.util.PhotoUtil;
import com.xbb.util.Result;
import com.xbb.util.Result1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户控制层
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/getUserList")
    public Object getUserList(UserParam userParam){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        if (!StringUtils.isEmpty(userParam.getLoginName())) {
            queryWrapper.like("login_name", userParam.getLoginName());
        }
        if (!StringUtils.isEmpty(userParam.getBeginTime())) {
            queryWrapper.gt("creat_time", userParam.getBeginTime());
        }
        if (!StringUtils.isEmpty(userParam.getEndTime())) {
            queryWrapper.lt("creat_time", userParam.getEndTime());
        }
        if (!StringUtils.isEmpty(userParam.getIsLockout())) {
            queryWrapper.eq("is_lockout", userParam.getIsLockout());
        }
        if(!StringUtils.isEmpty(userParam.getOrderBy()) && userParam.getOrderBy().equals("creatTime")) {
            queryWrapper.orderByDesc("creat_time",userParam.getCreatTime()); //字段名
        }
        if(!StringUtils.isEmpty(userParam.getOrderBy()) && userParam.getOrderBy().equals("lastLoginTime")) {
            queryWrapper.orderByDesc("last_login_time",userParam.getLastLoginTime()); //字段名
        }
        Page<User> page = new  Page<User>(userParam.getPage(),userParam.getLimit());
        IPage<User> iPage = userService.page(page, queryWrapper);
        List<User> data = iPage.getRecords();
        long total = iPage.getTotal();
        Result result = new Result(0, "用户列表", total, data);
        return result;
    }


    @PostMapping("/addUser")
    public Object addUser(@Valid User user){
        List<User> userNameByLoginName = userService.getUserNameByLoginName(user);
        Date date = new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(userNameByLoginName!=null && userNameByLoginName.size()>0){
            return new Result(2,"该用户已存在,不能重复添加！");
        }else{
            user.setCreatTime(sdf.format(date));
            user.setIsLockout("否");
            String md5 = MD5.getInstance().getMD5(user.getPassword());
            user.setPassword(md5);
            boolean save = userService.save(user);
            if(save) {
                return new Result(0,"添加成功");
            }else {
                return new Result(1,"添加失败");
            }
        }

    }


    @PostMapping("/updateUser")
    public Object updateUser(@RequestParam Integer id,@Valid User user){
        System.out.println(user);
        user.setId(id);
        boolean update = userService.updateById(user);
        if(update) {
            Result result = new Result(0, "修改成功");
            return result;
        }else {
            return new Result(1,"修改失败");
        }
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("/delUser")
    public Object delUser(@RequestParam Integer id) {
        List<User> userContainsRole = userService.getUserContainsRole(id);
        if(userContainsRole!=null && userContainsRole.size()>0){
            return new Result(2,"删除失败，该用户拥有角色,不能删除");
        }
        boolean remove = userService.removeById(id);
        if(remove) {
            return new Result(0,"删除成功");
        }else {
            return new Result(1,"删除失败");
        }
    }

    /**
     * 密码重置
     * @param id
     * @return
     */
    @PostMapping("/resetPsw")
    public Object resetPsw(@RequestParam Integer id) {
        User user = new User();
        user.setId(id);
        String password="ysd123";
        String md5 = MD5.getInstance().getMD5(password);
        user.setPassword(md5);
        boolean res=userService.updateById(user);
        if(res) {
            return new Result(0,"重置密码成功");
        }else {
            return new Result(1,"重置密码失败");
        }
    }

    /**
     * 用户锁定功能
     * @param id
     * @return
     */
    @PostMapping("/lock")
    public Object lock(@RequestParam Integer id) {
        User user=new User();
        user.setId(id);
        user.setIsLockout("是");
        boolean res=userService.updateById(user);
        if(res) {
            return new Result(0,"锁定成功");
        }else {
            return new Result(1,"锁定失败");
        }
    }

    /**
     * 用户解锁功能
     * @param id
     * @return
     */
    @PostMapping("/unlock")
    public Object unlock(@RequestParam Integer id) {
        User user=new User();
        user.setId(id);
        user.setIsLockout("否");
        boolean res=userService.updateById(user);
        if(res) {
            return new Result(0,"解锁成功");
        }else {
            return new Result(1,"解锁失败");
        }
    }

    /**
     * 员工签到
     * @param id
     * @return
     */
    @PostMapping("/qianDao")
    public Object qianDao(@RequestParam Integer id) {
        User user=userService.getById(id);
        if (user.getQiandaoState().equals("已签到")){
            return new Result(2,"你已经签到，无需重复签到");
        }
        user.setQiandaoState("已签到");
        user.setQiandaoTime(new Date());
        boolean res=userService.updateById(user);
        if(res) {
            return new Result(0,"签到成功");
        }else {
            return new Result(1,"签到失败");
        }
    }

    /**
     * 员工签退
     * @param id
     * @return
     */
    @PostMapping("/qianTui")
    public Object qianTui(@RequestParam Integer id) {
        User user=userService.getById(id);
        if (!user.getQiandaoState().equals("已签到")){
            return new Result(2,"你未签到，无需签退");
        }
        //当前时间在（签到+10分钟）之前，不允许签退
        Date time1 =new Date();
        Date time2 =new Date(user.getQiandaoTime().getTime()+60*1000*1);
        System.out.println("当前时间"+time1);
        System.out.println("签到时间+10分钟"+time2);
        if (time1.before(time2)){
            return new Result(2,"签退失败，距签到时间还未到10分钟");
        }
        user.setQiandaoState("已签退");
        user.setQiantuiTime(new Date());
        boolean res=userService.updateById(user);
        if(res) {
            return new Result(0,"签退成功");
        }else {
            return new Result(1,"签退失败");
        }
    }

    /**
     * 获取签到列表
     * @param user
     * @return
     */
    @PostMapping("/getQianDaoList")
    public Object getQianDaoList(UserParam user){
        List<User> list = userService.getQianDaoList(user);
        return new Result1(0,"签到列表",list.size(),list);
    }

    /**
     *获取咨询师列表
     * @param user
     * @return
     */
    @PostMapping("/getZiXunShiList")
    public Object getZiXunShiList(UserParam user){
        List<User> list = userService.getZiXunShiByWeight(user);
        user.setPage(null);
        user.setLimit(null);
        List<User> list2 = userService.getZiXunShiByWeight(user);
        return new Result1(0,"咨询师列表",list2.size(),list);
    }

    /**
     *获取网络咨询师列表
     * @param user
     * @return
     */
    @PostMapping("/getWangLuoZiXunShiList")
    public Object getWangLuoZiXunShiList(UserParam user){
        List<User> list = userService.getWangLuoZiXunShiList(user);
        user.setPage(null);
        user.setLimit(null);
        List<User> list2 = userService.getZiXunShiByWeight(user);
        return new Result1(0,"网络咨询师列表",list2.size(),list);
    }

    /**
     * 修改权重
     * @param user
     * @return
     */
    @PostMapping("/updateZiXunShiWeight")
    public Object updateZiXunShiWeight(User user){
        boolean update = userService.updateZiXunShiWeight(user);
        if(update) {
            return new Result(0,"修改权重成功");
        }else {
            return new Result(1,"修改权重失败");
        }
    }

   //0：已分配  1：待分配
   @RequestMapping("/weight")
   public Object weight(Integer id) {
       List<User> getzixunshi = userService.getZiXunShiByWeight(null);
       List<Integer> str=new ArrayList<Integer>();
       for(int i=0;i<getzixunshi.size();i++) {
           str.add(i, getzixunshi.get(i).getId());
       }
       boolean updateBatchUser = userService.updateBatchUser(str,id);
       if(id==0){
           if (updateBatchUser) {
               return new Result(0, "自动分配关闭");
           }else{
               return new Result(1, "分配关闭失败");
           }
       }else{
           if (updateBatchUser) {
               return new Result(0, "自动分配开启");
           }else{
               return new Result(1, "分配开启失败");
           }
       }
   }

    /**
     * 修改密码
     * @param loginName
     * @param user
     * @param oldPsw
     * @return
     */
    @RequestMapping("/updatePassWord")
    public Object updatePassWord(String loginName,User user,String oldPsw,String password){
        Integer integer=null;
        String md5 = MD5.getInstance().getMD5(oldPsw);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        User one = userService.getOne(queryWrapper);
        if(one.getPassword().equals(md5)){
            String md51 = MD5.getInstance().getMD5(password);
            user.setPassword(md51);
            integer = userService.updatePassWord(user);
        }else{
            return new Result(2,"原密码输入错误，请检查后再次输入");
        }
        if(integer>0){
            return new Result(0,"密码修改成功");
        }
        return new Result(1,"密码修改失败");
    }


    /**
     * 前台用户头像修改
     * @param id
     * @param imgurl
     * @return
     */
    @RequestMapping("/updateUserHp")
    public Object updateUserHp(Integer id,String imgurl) {
        User user = new User();
        user.setId(id);
        user.setImgUrl(imgurl);
        System.out.println(user);
        System.out.println(user.getImgUrl());

        boolean update = userService.updateById(user);
        if(update) {
            return new Result(0,"头像已上传成功");
        }
        return new Result(1,"头像上传失败");
    }

    /**
     * 用户拍照上传头像
     *
     * @return
     */
    @RequestMapping("/uploadHeadImg")
    public Object uploadHeadImg(String photo,Integer userId) {
        String[] split = photo.split(",");
        String s = split[1];
        Map<String, Object> map = new HashMap<String, Object>();
        String s1 = PhotoUtil.GenerateImage(s,userId,userService);
        if (!s1.equals("")) {
            map.put("success", true);
            map.put("message", s1);
        }
        else{
            map.put("success",true);
        }
        return map;
    }

}
